<template>
  <a-modal
    width="1200px"
    :bodyStyle="store.userStore.bodyStyle"
    v-model:open="modal.open"
    :title="modal.title"
    ok-text="确认"
    cancel-text="取消"
    @ok="modalConfirm"
    :maskClosable="false"
  >
    <a-form
      class="modelForm"
      ref="modelForm"
      :colon="false"
      :model="formState"
      :label-col="{ style: { width: '140px' } }"
    >
      <a-row :gutter="[16, 0]">
        <a-col :span="8">
          <a-form-item
            label="管理路径名称："
            :label-col="{ style: { width: '110px' } }"
            name="managePathName"
            required
            :rules="[
              {
                required: true,
                message: '管理路径名称不能为空',
                trigger: 'change'
              }
            ]"
          >
            <a-input
              style="width: 350px"
              :maxLength="50"
              v-model:value="formState.managePathName"
              autocomplete="off"
              placeholder="请输入管理路径名称"
              :disabled="modal.type === 'detail'"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item name="managePathName">
            <a-checkbox v-model:checked="formState.isSelect" :disabled="modal.type === 'detail'"
              >多选一路径</a-checkbox
            >
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item
            v-if="formState.createTime"
            label="创建时间"
            :label-col="{ style: { width: '110px' } }"
          >
            {{ formState.createTime }}
          </a-form-item>
        </a-col>
      </a-row>
      <a-row class="title">
        <a-col :span="24" style="padding-left: 16px; background-color: #f7f8fa">
          <span class="red">*</span> 管理路径内容：
        </a-col>
      </a-row>
      <!-- <a-row class="title">
            <a-col :span="18"> <span class="red">*</span> 管理路径触发事件： </a-col>
          </a-row> -->
      <div style="padding: 16px; margin-bottom: 24px; border: 1px solid rgb(229, 230, 235)">
        <a-row style="justify-content: space-between" :gutter="16">
          <a-col :span="16">
            <div style="height: 100%; padding: 16px; border: 1px solid #e5e6eb">
              <template v-for="(subitem, index) in formState.conditions" :key="index">
                <a-form-item
                  :ref="(el) => (conditionRef['c_' + index] = el)"
                  :label="'条件' + numberToChinese(index + 1) + ':'"
                  :label-col="{ style: { width: '100px' } }"
                  :name="['conditions', index]"
                  required
                  :rules="[
                    {
                      validator: condition_validator
                    }
                  ]"
                >
                  <a-row :gutter="[16, 0]">
                    <a-col :span="6">
                      <a-select
                        ref="select"
                        style="width: 100%"
                        name="eventType"
                        v-model:value="subitem.eventType"
                        @change="eventTypeChange(subitem)"
                        :disabled="modal.type === 'detail'"
                      >
                        <a-select-option
                          v-for="option in eventMaps"
                          :key="option.value"
                          :value="option.value"
                          >{{ option.label }}</a-select-option
                        >
                      </a-select>
                    </a-col>
                    <a-col :span="14">
                      <a-form-item-rest v-if="subitem.eventType === '患者标签'">
                        <a-input
                          :disabled="modal.type === 'detail' ? true : false"
                          name="result"
                          v-model:value="subitem.result"
                          @change="conditionRef['c_' + index].onFieldChange()"
                          placeholder="请输入事件名称"
                          autocomplete="off"
                        />
                      </a-form-item-rest>

                      <template v-else-if="subitem.eventType === '患者体征'">
                        <a-row :gutter="[8, 8]">
                          <a-form-item-rest>
                            <a-col :span="8">
                              <a-select
                                v-model:value="subitem.subEventType"
                                placeholder="体征"
                                @change="
                                  subEventTypeChange($event, subitem, () => {
                                    conditionRef['c_' + index].onFieldChange()
                                  })
                                "
                                :disabled="modal.type === 'detail' ? true : false"
                              >
                                <a-select-option
                                  v-for="(sign, index) in signs"
                                  :key="index"
                                  :value="sign.value"
                                  >{{ sign.label }}</a-select-option
                                >
                              </a-select>
                            </a-col>
                            <a-col :span="6">
                              <a-select
                                v-model:value="subitem.operator"
                                @change="conditionRef['c_' + index].onFieldChange()"
                                :disabled="modal.type === 'detail' ? true : false"
                              >
                                <a-select-option value="=">{{ '=' }}</a-select-option>
                                <a-select-option value=">">{{ '>' }}</a-select-option>
                                <a-select-option value="≥">{{ '≥' }}</a-select-option>
                                <a-select-option value="<">{{ '<' }}</a-select-option>
                                <a-select-option value="≤">{{ '≤' }}</a-select-option>
                                <a-select-option value="≠">{{ '≠' }}</a-select-option>
                              </a-select>
                            </a-col>
                          </a-form-item-rest>
                          <a-col :span="10">
                            <template v-if="subitem.subEventType">
                              <template v-if="signObj[subitem.subEventType].type === 'number'">
                                <a-form-item
                                  :name="['conditions', index, 'result']"
                                  required
                                  :rules="[
                                    {
                                      required: true,
                                      message: '请输入数字',
                                      pattern: new RegExp(/^\d+(\.\d{1,2})?$/)
                                    }
                                  ]"
                                >
                                  <a-input
                                    name="result"
                                    v-model:value="subitem.result"
                                    @input="conditionRef['c_' + index].onFieldChange()"
                                    :disabled="modal.type === 'detail' ? true : false"
                                    autocomplete="off"
                                  />
                                </a-form-item>
                              </template>
                              <template v-else-if="signObj[subitem.subEventType].type === 'text'">
                                <a-form-item-rest>
                                  <a-input
                                    v-model:value="subitem.result"
                                    @input="conditionRef['c_' + index].onFieldChange()"
                                    :disabled="modal.type === 'detail' ? true : false"
                                    autocomplete="off"
                                  />
                                </a-form-item-rest>
                              </template>
                              <template v-else-if="signObj[subitem.subEventType].type === 'select'">
                                <a-form-item-rest>
                                  <a-select
                                    v-model:value="subitem.result"
                                    @change="conditionRef['c_' + index].onFieldChange()"
                                    :disabled="modal.type === 'detail' ? true : false"
                                  >
                                    <a-select-option
                                      v-for="(option, index) in signObj[subitem.subEventType]
                                        .options"
                                      :value="option.value"
                                      :key="index"
                                      >{{ option.label }}</a-select-option
                                    >
                                  </a-select>
                                </a-form-item-rest>
                              </template>
                            </template>
                          </a-col>
                        </a-row>
                      </template>
                    </a-col>
                    <a-col :span="2" :offset="2">
                      <div class="icons">
                        <a-button
                          style="padding: 2px"
                          type="link"
                          danger
                          v-if="index"
                          :disabled="modal.type === 'detail'"
                          @click="nodeDel(formState.conditions, index)"
                          >删除</a-button
                        >
                        <!-- <DeleteOutlined
                              v-if="index"
                              @click="nodeDel(formState.conditions, index)"
                            /> -->
                        <a-button
                          style="padding: 2px"
                          type="link"
                          v-else
                          :disabled="modal.type === 'detail'"
                          @click="nodeAdd(formState.conditions)"
                          >新增</a-button
                        >
                        <!-- <PlusSquareOutlined v-else @click="nodeAdd(formState.conditions)" /> -->
                        <a-button
                          style="padding: 2px"
                          type="link"
                          :disabled="modal.type === 'detail'"
                          @click="nodeCopy(formState.conditions, subitem)"
                          >复制</a-button
                        >
                        <!-- <CopyOutlined @click="nodeCopy(formState.conditions, subitem)" /> -->
                      </div>
                    </a-col>
                  </a-row>
                </a-form-item>
              </template>
            </div>
          </a-col>
          <a-col :span="8">
            <div style="height: 100%; padding: 16px; border: 1px solid #e5e6eb">
              可选按钮
              <a-form-item>
                <div class="block" style="min-height: 40px; border-width: 0">
                  <div v-if="modal.type === 'detail'" class="mask" />
                  <a-tag color="#e8f7ff" class="tag" @click="tagAdd('(')">(</a-tag>
                  <a-tag color="#e8f7ff" class="tag" @click="tagAdd(')')">)</a-tag>
                  <a-tag color="#e8f7ff" class="tag" @click="tagAdd('and')">and</a-tag>
                  <a-tag color="#e8f7ff" class="tag" @click="tagAdd('or')">or</a-tag>
                  <a-tag color="#e8f7ff" class="tag" @click="tagAdd('not')">not</a-tag>
                  <a-tag
                    color="#e8f7ff"
                    class="tag"
                    v-for="(item, index) in formState.conditions"
                    @click="tagAdd(`条件${numberToChinese(index + 1)}`)"
                    :key="index"
                    >{{ `条件${numberToChinese(index + 1)}` }}</a-tag
                  >
                </div>
              </a-form-item>
              <span>编辑逻辑式</span>
              <a-form-item
                name="expression"
                :rules="[
                  {
                    validator: expressValidator
                  }
                ]"
              >
                <div class="block" style="margin-top: 8px">
                  <div v-if="modal.type === 'detail'" class="mask" />
                  <a-tag
                    color="#e8f7ff"
                    class="tag"
                    v-for="(tag, i) in formState.expression"
                    :key="i"
                    closable
                    v-model:visible="tag.visible"
                    @close="tagDelAfter(formState.expression, i)"
                    >{{ tag.label }}</a-tag
                  >
                </div>
              </a-form-item>
            </div>
          </a-col>
        </a-row>
      </div>
      <a-row class="title">
        <a-col :span="24" style="padding-left: 16px; background-color: #f7f8fa">
          <span class="red">*</span> 管理活动内容：
        </a-col>
      </a-row>
      <div style="padding: 16px; border: 1px solid rgb(229, 230, 235)">
        <template v-for="(item, i) in formState.pathManageTemplateVOList" :key="i">
          <a-form-item
            :ref="(el) => (conditionRef['p_' + index] = el)"
            :name="['pathManageTemplateVOList', i]"
            :rules="[
              {
                validator: tNodeValidator
              }
            ]"
          >
            <a-form-item-rest>
              <a-row :gutter="[16, 0]">
                <a-col :span="3">
                  <a-select
                    style="width: 100%"
                    v-model:value="item.templateType"
                    @change="
                      ($event) => {
                        tempChange($event, item)
                        conditionRef['p_' + index].onFieldChange()
                      }
                    "
                    :disabled="modal.type === 'detail'"
                  >
                    <a-select-option
                      v-for="option in tempMaps"
                      :key="option.value"
                      :value="option.value"
                      >{{ option.label }}</a-select-option
                    >
                  </a-select>
                </a-col>
                <a-col :span="5">
                  <a-select
                    style="width: 100%"
                    v-model:value="item.templateId"
                    show-search
                    @change="
                      ($event) => {
                        tempNameChange($event, item, tempMaps[item.templateTypeIndex].children)
                        conditionRef['p_' + index].onFieldChange()
                      }
                    "
                    :disabled="modal.type === 'detail'"
                    :placeholder="'请选择' + item.templateType"
                    :options="tempMaps[item.templateTypeIndex]?.children"
                  >
                    <!-- <a-select-option
                          v-for="(option, index) in tempMaps[item.templateTypeIndex]?.children"
                          :key="index"
                          :label="option.label"
                          :value="option.value"
                          >{{ option.label }}</a-select-option
                        > -->
                  </a-select>
                </a-col>
                <a-col :span="15">
                  <div class="row" v-if="[0, 1, 2, 4].includes(item.templateTypeIndex)">
                    <span v-if="[0, 2, 4].includes(item.templateTypeIndex)"> 执行日期： 第</span>
                    <span v-else> 循环周期： </span>
                    <a-input-number
                      min="1"
                      :precision="0"
                      :step="1"
                      style="width: 96px"
                      v-model:value="item.cronCycle"
                      autocomplete="off"
                      :disabled="modal.type === 'detail'"
                      @change="
                        ($event) => {
                          conditionRef['p_' + index].onFieldChange()
                        }
                      "
                    />
                    <span> 天 </span>
                  </div>
                  <div class="row" v-if="[5].includes(item.templateTypeIndex)">
                    <span> 执行日期： </span>
                    <div class="groups">
                      <a-checkbox
                        v-for="w in weeks"
                        :key="w.value"
                        :value="w.value"
                        :checked="item.cronDate.includes(w.value)"
                        @change="
                          ($event) => {
                            changeCronDate($event, item.cronDate)
                            conditionRef['p_' + index].onFieldChange()
                          }
                        "
                        :disabled="modal.type === 'detail'"
                        >{{ w.label }}</a-checkbox
                      >
                      <a-checkbox
                        :value="true"
                        :checked="item.cronDate.length === weeks.length"
                        :indeterminate="
                          item.cronDate.length && item.cronDate.length !== weeks.length
                            ? true
                            : false
                        "
                        @change="
                          () => {
                            weekAll(item)
                            conditionRef['p_' + index].onFieldChange()
                          }
                        "
                        :disabled="modal.type === 'detail'"
                      >
                        全选
                      </a-checkbox>
                    </div>
                    <span> 执行时间： </span>
                    <div class="times">
                      <div class="content" @click="pickerFocus(item)">
                        <div v-if="modal.type === 'detail'" class="mask" />
                        <a-tag
                          class="tag"
                          v-for="(tag, i) in item.cronTime"
                          @click.stop
                          :key="i"
                          closable
                          v-model:visible="tag.visible"
                          @close="
                            () => {
                              tagDel(item.cronTime, i)
                              conditionRef['p_' + index].onFieldChange()
                            }
                          "
                          >{{ tag.label }}</a-tag
                        >
                      </div>
                      <a-time-picker
                        class="pick"
                        v-model:open="item.open"
                        format="HH:mm"
                        valueFormat="HH:mm"
                        @change="
                          ($event) => {
                            conditionRef['p_' + index].onFieldChange()
                            cronTimePush($event, item)
                          }
                        "
                        :disabled="modal.type === 'detail'"
                      />
                    </div>
                  </div>
                </a-col>
                <a-col :span="1" style="display: flex; flex-direction: row-reverse">
                  <template v-if="modal.type !== 'detail'">
                    <icon-font
                      v-if="i == 0"
                      class="icon-plus"
                      type="icon-xinzeng"
                      @click="tNodeAdd(formState.pathManageTemplateVOList)"
                    />
                    <icon-font
                      v-else
                      class="icon-del"
                      type="icon-shanchu"
                      @click="tNodeDel(i, formState.pathManageTemplateVOList)"
                    />
                  </template>
                </a-col>
              </a-row>
            </a-form-item-rest>
          </a-form-item>
        </template>
      </div>

      <!-- <a-form-item v-if="modal.type !== 'detail'">
            <a-row>
              <a-button class="add" :icon="h(PlusOutlined)" @click="addNode">新增</a-button>
            </a-row>
          </a-form-item> -->
    </a-form>
    <template #footer>
      <template v-if="modal.type !== 'detail'">
        <a-button @click="modal.open = false">取消</a-button>
        <a-button :loading="modal.loading" type="primary" @click="modalConfirm">确认</a-button>
      </template>
      <template v-else>
        <!-- <a-button
              @click="modalUpdate"
              :disabled="formState.groupNames && formState.groupNames.length > 0 ? true : false"
              >编辑</a-button
            > -->
        <a-button @click="modalUpdate">编辑</a-button>
        <a-button type="primary" @click="modal.open = false">确认</a-button>
      </template>
    </template>
  </a-modal>
</template>

<script lang="ts" setup name="管理路径">
import { ref, reactive, createVNode, onMounted } from 'vue'
import store from '@/store'
import { message, Modal } from 'ant-design-vue'
import type { Form } from 'ant-design-vue'
import { ExclamationCircleFilled } from '@ant-design/icons-vue'
import { numberToChinese } from '@/utils/tools'
import { getTemplateList, manageAdd, manageUpdate, manageInfo } from '@/api/manage'
import _ from 'lodash'

const props = defineProps(['diseaseType'])

const conditionRef = reactive({})

const tempMaps = [
  {
    label: '健康处方',
    value: '健康处方',
    children: []
  },
  {
    label: '健康宣教',
    value: '健康宣教',
    children: []
  },
  {
    label: '健康随访',
    value: '健康随访',
    children: []
  },
  {
    label: '健康监测',
    value: '健康监测',
    children: []
  },
  {
    label: '就诊提醒',
    value: '就诊提醒',
    children: []
  },
  {
    label: '用药提醒',
    value: '用药提醒',
    children: []
  },
  {
    label: '饮食方案',
    value: '饮食方案',
    children: []
  },
  {
    label: '运动方案',
    value: '运动方案',
    children: []
  }
]

onMounted(() => {
  getTemplateList({
    templateAffiliation: '公共模板',
    platformId: store.userStore.platformId
  }).then((res) => {
    if (res.data) {
      res.data.map((v) => {
        v.label = v.templateName
        v.value = v.id
        const i = tempMaps.findIndex((u) => {
          return u.value === v.templateType
        })
        if (i !== -1) {
          tempMaps[i].children = [...tempMaps[i].children, v]
        }
      })
    }
  })
})

const modelForm = ref<Form>(null)

const modal = reactive({
  open: false,
  type: 'save',
  loading: false,
  title: '新增管理路径'
})

type Condition = {
  eventType: string
  result: string
  subEventType: string
  operator: string
}

type PathManageTemplateVO = {
  templateId: undefined | number
  templateName: string
  templateType: string
  cronCycle: number
  cronDate: Array<string | never>
  cronTime: Array<Tag | never>
}

type Tag = {
  label: string
  visible: boolean
}

type FormState = {
  id: string
  createTime: string
  managePathName: string
  isSelect: boolean
  summary: string
  conditions: Condition[]
  expression: Array<Tag | never>
  pathManageTemplateVOList: PathManageTemplateVO[]
}

const formState = reactive<FormState>({
  id: '',
  createTime: '',
  managePathName: '',
  isSelect: true,
  summary: '',
  conditions: [
    {
      // title: '条件一',
      eventType: '',
      subEventType: '',
      result: '',
      operator: ''
    }
  ],
  expression: [],
  pathManageTemplateVOList: [
    {
      templateId: undefined,
      templateName: '',
      templateType: '',
      cronCycle: 30,
      cronDate: [],
      cronTime: []
    }
  ]
})

const formState_reset = (item?: FormState) => {
  modal.loading = false
  if (item) {
    Object.assign(formState, item)
  } else {
    Object.assign(formState, {
      id: '',
      createTime: '',
      managePathName: '',
      isSelect: true,
      summary: '',
      conditions: [
        {
          // title: '条件一',
          eventType: '',
          subEventType: '',
          result: '',
          operator: ''
        }
      ],
      expression: [],
      pathManageTemplateVOList: [
        {
          templateId: undefined,
          templateName: '',
          templateType: '',
          cronCycle: 30,
          cronDate: [],
          cronTime: []
        }
      ]
    })
  }
}

const eventMaps = computed(() => {
  if (props.diseaseType === 'checkAfter') {
    return [
      {
        label: '患者标签',
        value: '患者标签'
      }
    ]
  } else {
    return [
      {
        label: '患者体征',
        value: '患者体征'
      }
    ]
  }
})

// const ArrayFind = (arr, name, key = 'value') => {
//   const item = arr.find((v) => {
//     return v[key] === name
//   })
//   if (item) {
//     return item
//   } else {
//     return null
//   }
// }

const signObj = {
  性别: {
    type: 'select',
    options: [
      {
        label: '男',
        value: '男'
      },
      {
        label: '女',
        value: '女'
      }
    ]
  },
  身高: {
    type: 'number'
  },
  BMI: {
    type: 'number'
  },
  慢性病: {
    type: 'select',
    options: [
      {
        label: '2型糖尿病',
        value: '2型糖尿病'
      },
      {
        label: '高血压',
        value: '高血压'
      },
      {
        label: '痛风',
        value: '痛风'
      },
      {
        label: '冠心病',
        value: '冠心病'
      },
      {
        label: '睡眠呼吸暂停综合征',
        value: '睡眠呼吸暂停综合征'
      },
      {
        label: '心肌梗死',
        value: '心肌梗死'
      },
      {
        label: '脑卒中',
        value: '脑卒中'
      },
      {
        label: '非酒精性脂肪性肝病',
        value: '非酒精性脂肪性肝病'
      },
      {
        label: '骨关节炎',
        value: '骨关节炎'
      },
      {
        label: '多囊卵巢综合征',
        value: '多囊卵巢综合征'
      }
    ]
  },
  腰围: {
    type: 'number'
  },
  血压: {
    type: 'select',
    options: [
      {
        label: '血压异常',
        value: '血压异常'
      }
    ]
  },
  血糖: {
    type: 'select',
    options: [
      {
        label: '血糖异常',
        value: '血糖异常'
      }
    ]
  },
  血脂: {
    type: 'select',
    options: [
      {
        label: '血脂异常',
        value: '血脂异常'
      }
    ]
  },
  尿酸: {
    type: 'select',
    options: [
      {
        label: '尿酸异常',
        value: '尿酸异常'
      }
    ]
  }
}

const signs = [
  {
    label: '性别',
    value: '性别'
  },
  {
    label: '身高',
    value: '身高'
  },
  {
    label: 'BMI',
    value: 'BMI'
  },
  {
    label: '慢性病',
    value: '慢性病'
  },
  {
    label: '腰围',
    value: '腰围'
  },
  {
    label: '血压',
    value: '血压'
  },
  {
    label: '血糖',
    value: '血糖'
  },
  {
    label: '血脂',
    value: '血脂'
  },
  {
    label: '尿酸',
    value: '尿酸'
  }
]

const eventTypeChange = (subitem) => {
  subitem.subEventType = ''
  subitem.operator = ''
  subitem.result = ''
}

const subEventTypeChange = (e, subitem, callback) => {
  if (e) {
    subitem.operator = ''
    subitem.result = ''
  }
  callback()
}

const nodeAdd = (list: Condition[]) => {
  list.push({
    eventType: '',
    subEventType: '',
    result: '',
    operator: ''
  })
  formState.expression = []
}

const nodeCopy = (list: Condition[], item: Condition) => {
  list.push(_.cloneDeep(item))
  formState.expression = []
}

const tagAdd = (str: string) => {
  formState.expression.push({
    label: str,
    visible: true
  })
  modelForm.value?.clearValidate('expression')
}

const nodeDel = (list: Condition[], index: number) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      list.splice(index, 1)
      formState.expression = []

      if (list.length == 1) {
        modelForm.value?.clearValidate('expression')
      }
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const expressValidator = async (_, value) => {
  if (formState.conditions.length >= 2) {
    if (!value.length) {
      return Promise.reject(new Error('请完善条件'))
    } else {
      return Promise.resolve()
    }
  } else {
    return Promise.resolve()
  }
}

const condition_validator = async (_, value) => {
  if (value.eventType === '患者标签' && value.result) {
    return Promise.resolve()
  } else if (
    value.eventType === '患者体征' &&
    value.subEventType &&
    value.operator &&
    value.result
  ) {
    return Promise.resolve()
  } else {
    return Promise.reject(new Error('请完善条件'))
  }
}

const tNodeValidator = async (_, value) => {
  if (value.templateType == '饮食方案' || value.templateType == '运动方案') {
    const someTempType = formState.pathManageTemplateVOList.filter(
      (item) => item.templateType == value.templateType
    )
    if (someTempType.length > 1) {
      return Promise.reject(`最多只能添加一条${value.templateType}`)
    }
  }

  if (!value.templateId) {
    return Promise.reject('请完善内容')
  } else if (
    [5].includes(value.templateTypeIndex) &&
    (!value.cronDate.length || !value.cronTime.length)
  ) {
    return Promise.reject('请完善内容')
  } else {
    const sameData = formState.pathManageTemplateVOList.filter(
      (item) => item.templateId == value.templateId && item.cronCycle == value.cronCycle
    )
    if (sameData.length > 1) {
      return Promise.reject('模板名称不能重复')
    } else {
      return Promise.resolve()
    }
  }
}

const tempChange = (e, item) => {
  console.log(e, item)
  item.templateType = e
  item.templateTypeIndex = tempMaps.findIndex((v) => {
    return v.value === e
  })
  item.templateId = undefined
  item.templateName = ''
}

const tempNameChange = (e, item, list) => {
  item.templateId = e
  item.templateName = list.find((v) => {
    return v.id === e
  })?.templateName

  // if (item.templateType == '健康监测') {
  //   const vo = list.find((v) => {
  //   return v.id === e
  // })?.content
  // item.cronDate = JSON.parse(vo).cronDate.split(',')
  // item.cronTime = JSON.parse(vo).cronTime.split(',')
  // }
  console.log(e, item, list)
}

const changeCronDate = (e, list) => {
  console.log(e.target.value)
  const value = e.target.value
  if (list.includes(value)) {
    const i = list.findIndex((v) => {
      return v === value
    })
    list.splice(i, 1)
  } else {
    list.push(value)
  }
}

const weeks = [
  {
    label: '周一',
    value: '周一'
  },
  {
    label: '周二',
    value: '周二'
  },
  {
    label: '周三',
    value: '周三'
  },
  {
    label: '周四',
    value: '周四'
  },
  {
    label: '周五',
    value: '周五'
  },
  {
    label: '周六',
    value: '周六'
  },
  {
    label: '周日',
    value: '周日'
  }
]

const weekAll = (item: PathManageTemplateVO) => {
  if (item.cronDate.length !== weeks.length) {
    item.cronDate = weeks.map((v) => {
      return v.value
    })
  } else {
    item.cronDate = []
  }
}

const tNodeAdd = (list: PathManageTemplateVO[]) => {
  list.push({
    templateId: undefined,
    templateName: '',
    templateType: '',
    cronCycle: 30,
    cronDate: [],
    cronTime: []
  })
}

const tNodeDel = (index: number, list: PathManageTemplateVO[]) => {
  Modal.confirm({
    title: '删除',
    icon: createVNode(ExclamationCircleFilled, {
      style: {
        color: 'var(--color--danger)'
      }
    }),
    content: '确认是否删除',
    okText: '确定',
    okButtonProps: {
      danger: true,
      type: 'primary'
    },
    cancelText: '取消',
    onOk() {
      console.log('OK')
      list.splice(index, 1)
    },
    onCancel() {
      console.log('Cancel')
    }
  })
}

const convert = (content, flag) => {
  const {
    id,
    createTime,
    managePathName,
    isSelect,
    conditions,
    expression,
    pathManageTemplateVOList
  } = _.cloneDeep(content)
  if (flag) {
    const data = {
      id,
      createTime,
      managePathName,
      isSelect,
      conditions: JSON.stringify(
        conditions.map((v, i) => {
          v.title = '条件' + numberToChinese(i + 1)
          return v
        })
      ),
      //   expression: expression.join(' '),
      expression: expression.reduce((p, c) => {
        if (p) {
          return p + ' ' + c.label
        } else {
          return c.label
        }
      }, ''),
      pathManageTemplateVOList: pathManageTemplateVOList.map((v) => {
        if ([0, 1, 2, 4].includes(v.templateTypeIndex)) {
          v.cronDate = ''
          v.cronTime = ''
        } else {
          v.cronCycle = ''
          v.cronDate = v.cronDate.join(',')
          //   v.cronTime = v.cronTime.join(',')
          v.cronTime = v.cronTime.reduce((p, c) => {
            if (p) {
              return p + ',' + c.label
            } else {
              return c.label
            }
          }, '')
        }
        return v
      })
    }
    return data
  } else {
    const data = {
      id,
      createTime,
      managePathName,
      isSelect,
      conditions: JSON.parse(conditions).map((v) => {
        delete v.title
        return v
      }),
      expression: expression.split(' ').map((v) => {
        return {
          label: v,
          visible: true
        }
      }),
      pathManageTemplateVOList: pathManageTemplateVOList.map((v) => {
        if ([0, 1, 2, 4].includes(v.templateTypeIndex)) {
          v.cronDate = []
          v.cronTime = []
        } else {
          v.cronCycle = 30
          v.cronDate = v.cronDate.split(',')
          v.cronTime = v.cronTime.split(',').map((v) => {
            return {
              label: v,
              visible: true
            }
          })
        }
        return v
      })
    }
    return data
  }
}

const modalShow = (item) => {
  modelForm.value?.clearValidate()
  if (item) {
    manageInfo(item.id).then((res) => {
      console.log(res)
      modal.title = '管理路径详情'
      modal.type = 'detail'
      // const obj = convert({
      //   ...item,
      //   pathManageTemplateVOList: res.data.map((v) => {
      //     const index = tempMaps.findIndex((u) => {
      //       return u.value === v.templateType
      //     })
      //     return {
      //       templateId: v.templateId,
      //       templateName: v.templateName,
      //       templateType: v.templateType,
      //       templateTypeIndex: index,
      //       cronCycle: v.cronCycle,
      //       cronDate: v.cronDate,
      //       cronTime: v.cronTime
      //     }
      //   }, false)
      // })
      res.data.pathManageTemplateVOList.map((v) => {
        const index = tempMaps.findIndex((u) => {
          return u.value === v.templateType
        })
        v.templateTypeIndex = index
      })
      const obj = convert(res.data, false)
      console.log(obj)
      formState_reset(obj)
      modal.open = true
    })
  } else {
    modal.title = '新增管理路径'
    modal.type = 'save'
    formState_reset()
    modal.open = true
  }
}

const modalConfirm = () => {
  modelForm.value
    .validate()
    .then(() => {
      console.log('表单验证通过')
      modal.loading = true

      const params = convert(formState, true)
      params.diseaseType = props.diseaseType
      console.log(params)
      params.pathManageTemplateVOList.map((v) => {
        delete v.creator
      })

      if (formState.conditions.length === 1) {
        params.expression = '条件一'
      }

      const dietList = params.pathManageTemplateVOList.filter((v) => {
        return v.templateType === '饮食方案'
      })

      if (dietList.length == 0) {
        message.error('请至少添加一条饮食方案')
        modal.loading = false
        return
      }

      const sportList = params.pathManageTemplateVOList.filter((v) => {
        return v.templateType === '运动方案'
      })

      if (sportList.length == 0) {
        message.error('请至少添加一条运动方案')
        modal.loading = false
        return
      }

      if (modal.type === 'save') {
        manageAdd(params)
          .then((res) => {
            message.success('新建成功')
            modal.loading = false
            modal.open = false
            // conditionReset()
            emit('save')
          })
          .catch((e) => {
            modal.loading = false
          })
      } else {
        manageUpdate(params)
          .then((res) => {
            message.success('编辑成功')
            modal.loading = false
            modal.open = false
            // init()
            // getList()
            emit('update')
          })
          .catch((e) => {
            modal.loading = false
          })
      }
    })
    .catch((e) => {
      console.log(e)
    })
}

const modalUpdate = () => {
  modal.type = 'update'
  modal.title = '编辑管理路径'
}

const pickerFocus = (item) => {
  item.open = true
}

const tagDelAfter = (list, i) => {
  list.splice(i, list.length - i)
}

const tagDel = (list, i) => {
  list.splice(i, 1)
}

const cronTimePush = (e, item) => {
  console.log(e, item)
  const set = new Set(item.cronTime.map((v) => v.label))
  set.add(e)
  item.cronTime = Array.from(set).map((v) => {
    return {
      label: v,
      visible: true
    }
  })
}

defineExpose({
  modalShow
})

const emit = defineEmits(['save', 'update'])
</script>

<style lang="less" scoped>
@import url('../index.less');

.ant-form .ant-select.ant-select-in-form-item {
  width: 100%;
}

.row {
  display: flex;
  flex-direction: row;
  gap: 8px;
  align-items: center;
  width: 100%;
  white-space: nowrap;

  div {
    flex: 0 0 auto;
  }

  .times {
    flex: 1 1 auto;
  }
}

.ant-form .ant-input {
  width: 100% !important;
}

.modelForm {
  .bar {
    margin-bottom: 12px;
    border: 1px solid #e5e6eb;
  }

  .node {
    padding-bottom: 1px;
    margin: 0 0 10px;
    background: #f7f8fa;
  }

  .ant-form-item {
    margin-bottom: 8px;
  }

  .red {
    color: #f56667;
  }

  .title {
    width: 100%;
    height: 32px;
    margin-bottom: 16px;
    font-size: 14px;
    font-weight: 500;
    line-height: 32px;
  }

  .add {
    // width: 1160px;
    height: 32px;
    font-size: 14px;
    font-weight: 400;
    line-height: 22px;
    color: #165dff;
    border-color: #165dff;
  }

  .icon-plus,
  .icon-del {
    font-size: 16px;
  }

  .icon-plus {
    color: #165dff;
  }

  .icon-del {
    color: #f53f3f;
  }
}

.icons {
  display: flex;
  flex-direction: row-reverse;
  gap: 6px;
  align-items: center;
  width: 100%;
  height: 100%;
  font-size: 20px;
}

.block {
  position: relative;
  display: flex;
  flex-flow: row wrap;
  gap: 6px;
  align-content: flex-start;
  width: 100%;
  min-height: 88px;
  padding: 6px;
  overflow: hidden auto;
  border: 1px solid #e5e6eb;

  .tag {
    margin-right: 0;
    cursor: pointer;
  }
}

.times {
  position: relative;

  .content {
    display: flex;
    flex-flow: row wrap;
    gap: 6px;
    width: 100%;
    min-height: 34px;
    max-height: 84px;
    padding: 6px;
    overflow: hidden auto;
    line-height: 22px;
    border: 1px solid var(--color--primary);
  }

  .pick {
    position: absolute;
    top: 0;
    left: 0;
    z-index: -1;
    height: 32px;
    line-height: 22px;
  }
}

.mask {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 99;
  width: 100%;
  height: 100%;
  background-color: #f7f8fa5e;
}

.groups {
  display: flex;
  flex-flow: row wrap;
  gap: 6px;
  width: 280px;
}

.modal2 {
  .table {
    display: inline-flex;
    flex-direction: column;
    width: 100%;
    text-align: center;

    .td {
      display: flex;
      flex-direction: row;
      align-items: center;
      width: 100%;

      div {
        flex: 0 0 auto;
        padding: 8px;
        word-break: break-all;
      }
    }

    .name {
      width: 30%;
    }

    .content {
      width: 50%;
    }

    .action {
      width: 20%;

      .icon-move {
        font-size: 24px;
        line-height: 32px;
        color: #4e5969;
        cursor: move;
      }
    }

    .drag {
      width: 100%;
    }
  }
}
</style>
